﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DentScan2.WebApp
{
    public partial class Search : Classes.BaseForm
    {
        [System.ComponentModel.DefaultValue(1)]
        public int PageNum
        {
            get
            {
                return int.Parse(ViewState["PageNum"].ToString());
            }
            set
            {
                ViewState["PageNum"] = value;
            }
        }

        [System.ComponentModel.DefaultValue(20)]
        public int PageSize
        {
            get
            {
                return int.Parse(ViewState["PageSize"].ToString());
            }
            set
            {
                ViewState["PageSize"] = value;
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            this.CheckLogged();
            if (!IsPostBack)
            {
                this.PageNum = 1;
                this.PageSize = 30;
                tbChassisNumber.Text = string.IsNullOrEmpty(Request.QueryString["chassis"]) ? "" : Request.QueryString["chassis"];
                tbRegNumber.Text = string.IsNullOrEmpty(Request.QueryString["regno"]) ? "" : Request.QueryString["regno"];
                DoSearch();
            }
        }

      

        private void DoSearch()
        {
            var result = dl.pDamageSearch
                (
                tbName.Text == "" ? null : tbName.Text,
                tbIdentifier.Text == "" ? null : tbIdentifier.Text,
                tbDamageIdentifier.Text == "" ? -1 : Convert.ToInt32(tbDamageIdentifier.Text),
                ucRegional.CityId,
                ucRegional.DistrictId,
                ucRegional.CountryId,
                tbContactPerson.Text == "" ? null : tbContactPerson.Text,
                tbRegNumber.Text == "" ? null : tbRegNumber.Text,
                ucVehicles.MakeId,
                ucVehicles.ModelId,
                tbChassisNumber.Text == "" ? null : tbChassisNumber.Text,
                ucInsDDL.SelectedId,
                UcEvaluatorDDL.SelectedId,
                tbDamageCode.Text == "" ? null : tbDamageCode.Text,
                tbDocumentNumber.Text == "" ? null : tbDocumentNumber.Text,
                (this.PageNum - 1) * this.PageSize + 1,
                this.PageSize
                ).ToArray();

            

            if (result.Length == 0)
            {
                bPrev.Visible = false;
                bNext.Visible = false;
                rResults.Visible = false;
                lRecordCount.Text = "0";
            }
            else
            {
                int totalCount = Convert.ToInt32(result[0].rn + result[0].rnrev - 1);
                bPrev.Visible = this.PageNum>1;
                bNext.Visible = (this.PageNum) * this.PageSize < totalCount;
                rResults.Visible = true;
                rResults.DataSource = result;
                rResults.DataBind();
                lRecordCount.Text = totalCount.ToString();
            }
        }

        private void ChangePage(int inc)
        {
            this.PageNum += inc;
            DoSearch();

        }

        protected void bSearch_Click(object sender, EventArgs e)
        {
            this.PageNum = 1;
            DoSearch();
        }

        protected void bPrev_Click(object sender, EventArgs e)
        {
            ChangePage(-1);
        }

        protected void bNext_Click(object sender, EventArgs e)
        {
            ChangePage(1);
        }

        private void DeleteDamage(string damageId)
        {
            var d = dl.Damages.First(dd => dd.DamageId == Guid.Parse(damageId));
            d.IsDel = true;
            d.LastEditDate = DateTime.Now;
            dl.SubmitChanges();
            DoSearch();

        }

        public bool IsAdmin()
        {
            return (this.Level == 1);
        }


        protected void rResults_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DEL": DeleteDamage(e.CommandArgument.ToString()); break;
                case "ARCHIVES": ShowArhives(e.CommandArgument.ToString()); break;
            }
        }

        private void ShowArhives(string damageId)
        {
            var archives = dl.DamageArhives.Where(da => !da.IsDel && da.DamageId == Guid.Parse(damageId));
            var ds = (from a in archives
                      select new { 
                          UID= Guid.NewGuid().ToString(), 
                          Area=this.AreaId.ToString(), 
                          Date = a.ArhiveDate.ToShortDateString(),
                          ArchiveId = a.DamageArhiveId.ToString()
                      }).ToArray();
            
            foreach (var row in ds)
                Cache.Add(row.UID, row.ArchiveId, null, DateTime.Now.AddHours(10), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Low, null);
            rArchive.DataSource = ds;
            rArchive.DataBind();
            mvSearch.SetActiveView(vArchive);
        }

        protected void bBack_Click(object sender, EventArgs e)
        {
            mvSearch.SetActiveView(vSearch);
        }
    }
}